﻿using System.Net;
using System.Net.Sockets;
using System.Text;

using GCC.Container.Abstracts;

namespace GCC.Container.Comm.TCP.Default
{
    public class Client : AbsCommTcpClient<string>
    {
        /// <summary>
        /// 默认flag信息
        /// </summary>
        private readonly byte[] _flagInfo = new byte[] { 0x55, 0xaa };
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="targetIp">目标IP</param>
        /// <param name="logger">日志</param>
        /// <param name="name">名称</param>
        /// <param name="localInfo">本地地址信息</param>
        public Client(IPEndPoint targetIp, AbsGCCLogger logger, string name, IPEndPoint? localInfo) : base(targetIp, logger, name, localInfo)
        {
        }

        public Client(IPEndPoint targetIp, AbsGCCLogger logger, string name, Socket socket) : base(targetIp, logger, name, socket)
        {
        }

        /// <summary>
        /// 检查flag
        /// </summary> 
        /// <returns></returns>
        protected override bool CheckFlag(in Memory<byte> flagBuffer)
        {
            return flagBuffer.Span.SequenceEqual(_flagInfo);
        }

        /// <summary>
        /// 检查头
        /// </summary> 
        /// <returns></returns>
        protected override bool CheckHeader(in Memory<byte>? _, in Memory<byte> headBuffer, out int bodyLength)
        {
            bodyLength = BitConverter.ToInt32(headBuffer.Span);
            return true;
        }

        /// <summary>
        /// 处理数据
        /// </summary> 
        /// <returns></returns>
        protected override string HandleData(in Memory<byte>? _, in Memory<byte> __, in Memory<byte> bodyBuffer)
        {
            return Encoding.UTF8.GetString(bodyBuffer.Span);
        }

        protected override int GetBodyLengh(string data)
        {
            return Encoding.UTF8.GetByteCount(data);
        }

        protected override void PutData(in Memory<byte>? _, in Memory<byte> __, Memory<byte> bodyBuffer, in string data)
        {
            Encoding.UTF8.GetBytes(data).CopyTo(bodyBuffer.Span);
        }

        protected override void PutFlag(Memory<byte> flagBuffer)
        {
            _flagInfo.CopyTo(flagBuffer);
        }

        protected override void PutHeader(in Memory<byte>? _, Memory<byte> headBuffer, in string data)
        {
            BitConverter.GetBytes(GetBodyLengh(data)).CopyTo(headBuffer);
        }
    }
}
